<?php
/**
 * @user: thanatos <thanatos915@163.com>
 */

namespace common\models;

use Yii;
use yii\base\Model;

class GenerateCode extends Model
{
    public $number;
    public $product_id;

    public function rules()
    {
        return [
            [['number', 'product_id'], 'integer']
        ];
    }

    /**
     * @param $params
     * @return bool
     * @throws \yii\base\Exception
     * @throws \yii\db\Exception
     * @author thanatos <thanatos915@163.com>
     */
    public function submit($params)
    {
        $this->load($params, '');
        if (!$this->validate()) {
            return false;
        }

        $productModel = Product::findOne(['id' => $this->product_id]);
        if (empty($productModel)) {
            $this->addError('product_id', '产品不存在');
            return false;
        }

        $data = [];
        $app = Yii::$app->wechat->official;
        for ($i=0; $i < $this->number; $i++) {
            $securitySn = Yii::$app->security->generateRandomString(10);
            $code = $productModel->code;
            for ($j=0; $j<7; $j++) {
                $code .= rand(0, 9);
            }
            $result = $app->qrcode->forever($securitySn);
            $data[] = [
                'goods_sn' => $productModel->goods_sn,
                'security_sn' => $securitySn,
                'bar_code' => $code,
                'identity_code' => $code,
                'link' => $result['url'],
                'price' => $productModel->price,
                'status' => 10,
                'created_at' => time(),
                'updated_at' => time()
            ];
        }

        Yii::$app->db->createCommand()->batchInsert(Code::tableName(), [
            'goods_sn', 'security_sn', 'bar_code', 'identity_code', 'link', 'status', 'created_at', 'updated_at'
        ], $data)->execute();
        return true;
    }

}